const path = require("path");
const {
  createNews,
  findNews,
  newsPublish,
  delNews,
  findANew,
  updateById,
} = require("../../services/admin/news.service");
const {
  unSupportedFileType,
  invalidNewsID,
} = require("../../constant/err.type");

class NewsController {
  //   async upload(ctx, next) {
  //     //files后边跟.文件名
  //     // console.log(ctx.request.files.file);
  //     const { file } = ctx.request.files;
  //     const fileTypes = ["image/jepg", "image/png"];
  //     if (file) {
  //       if (!fileTypes.includes(file.mimetype)) {
  //         return ctx.app.emit("error", unSupportedFileType, ctx);
  //       }
  //       ctx.body = {
  //         code: 0,
  //         message: "图片上传成功",
  //         result: {
  //           goods_img: path.basename(file.filepath), //拿到文件名
  //         },
  //       };
  //       // await next();
  //     } else {
  //       return ctx.app.emit("error", fileUploadError, ctx);
  //     }
  //   }

  async addNews(ctx) {
    //files后边跟.文件名
    // console.log(ctx.request.files.file);

    try {
      //拿到要创建的数据
      const { title, content, category, isPublish } = ctx.request.body;
      let cover = "";
      const { file } = ctx.request.files;
      const fileTypes = ["image/jpeg", "image/png", "image/jpg"];
      if (file) {
        if (!fileTypes.includes(file.mimetype)) {
          return ctx.app.emit("error", unSupportedFileType, ctx);
        }
        //public 作为静态资源目录 直接用其相对位置
        cover = `/newsuploads/${path.basename(file.filepath)}`;
      }
      const res = await createNews({
        title,
        content,
        category,
        isPublish,
        cover,
        editTime: new Date(),
      });
      if (res && cover) {
        ctx.body = {
          code: 0,
          message: "添加新闻成功",
          result: {
            title,
            content,
            category,
            isPublish,
            cover,
            editTime: new Date(),
          },
        };
      } else {
        //如果没有头像传到后端，就不返回头像
        ctx.body = {
          code: 1,
          message: "添加新闻失败",
          result: {
            // goods_img: path.basename(file.filepath), //拿到文件名
            user_name,
            gender,
            introduction,
          },
        };
      }
    } catch (error) {
      console.error("添加新闻过程中出现错误:", error);
      ctx.body = {
        code: 1,
        message: "添加新闻失败",
      };
    }
  }

  async publish(ctx) {
    const res = await newsPublish({
      ...ctx.request.body,
      editTime: new Date(),
    });
    if (res) {
      ctx.body = {
        code: 0,
        message: "发布状态修改成功",
      };
    }
  }

  async updateList(ctx) {
    try {
      //拿到要修改的数据
      const { title, content, category, isPublish, id } = ctx.request.body;
      let cover = "";
      const { file } = ctx.request.files;
      const fileTypes = ["image/jpeg", "image/png", "image/jpg"];
      if (file) {
        if (!fileTypes.includes(file.mimetype)) {
          return ctx.app.emit("error", unSupportedFileType, ctx);
        }
        //public 作为静态资源目录 直接用其相对位置
        cover = `/newsuploads/${path.basename(file.filepath)}`;
      }
      const res = await updateById({
        id,
        title,
        content,
        category,
        isPublish,
        cover,
        editTime: new Date(),
      });
      if (res && cover) {
        ctx.body = {
          code: 0,
          message: "更新新闻成功",
          result: {
            title,
            content,
            category,
            isPublish,
            cover,
            editTime: new Date(),
          },
        };
      } else {
        //如果没有头像传到后端，就不返回头像
        ctx.body = {
          code: 1,
          message: "更新新闻失败",
        };
      }
    } catch (error) {
      console.error("更新新闻过程中出现错误:", error);
      ctx.body = {
        code: 1,
        message: "更新新闻失败",
      };
    }
  }

  async delList(ctx) {
    try {
      const res = await delNews(ctx.params.id);

      if (res !== null) {
        ctx.body = {
          code: 0,
          message: "新闻删除成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", invalidNewsID, ctx);
      }
    } catch (error) {
      console.error(error);
    }
  }

  async findAll(ctx) {
    //1.解析pageNum和pageSize
    const { pageNum = 1, pageSize = 10 } = ctx.request.query;
    //2.调用数据处理的相关方法
    const res = await findNews(pageNum, pageSize);
    //3.返回结果
    console.log(res);

    ctx.body = {
      code: 0,
      message: "获取商品列表成功",
      result: res,
    };
  }

  async findOne(ctx) {
    const res = await findANew({ id: ctx.params.id });
    if (res) {
      ctx.body = {
        code: 0,
        message: "获取新闻信息成功",
        result: res,
      };
    }
  }
}

module.exports = new NewsController();
